<?php

namespace Database\Seeders;

use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class UsersSeeder extends Seeder
{
    // php artisan db:seed --class=UsersSeeder

    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        // 清空数据表 后在添加
        $model = new User();
        $table = DB::table('user');
        $table->truncate();

        // ALTER TABLE `art_user` AUTO_INCREMENT=501;
        DB::statement('ALTER TABLE `art_user` AUTO_INCREMENT=500;');

        // 使用循环创建数据
        $time = time();
        for($x = 0; $x <= 30; $x++){
            $_row = $this->makeRow($model, $time, $x);
            // 保存数据到数据库中
            $table->insert($_row);
        }

        // 完善数据
        // 用户名 =（五位随机字符串） id + 手机号 取后四位
        $users = $table->get();
        $users = json_decode(json_encode($users), true);
        foreach($users as $_user){
            $username = $_user['salt'].substr($_user['id'] + $_user['mobile'], -4);
            DB::table('user')->where('id', $_user['id'])->update(['username' => $username]);
        }
    }

    // 生成数据
    protected function makeRow($model, $time, $index)
    {
        // 手机号
        $mobile = 13123456780 + $index;
        if($index >= 10 && $index < 20){
            $mobile = 15123456770 + $index;
        } elseif($index >= 20 && $index < 30){
            $mobile = 18123456760 + $index;
        }

        // 其他参数
        $_nums = mt_rand(30, 70);
        $_sex  = mt_rand(0, 2);
        $_salt = $this->random($model, 5);
        $_row  = [
            'username' => '',
            'password' => $model->add_md5('123456', $_salt),
            'salt'     => $_salt,
            'nickname' => '',
            'head_img' => 'https://img.shenlanhui.com/static/head_img/face_'.rand(1, 450).'.jpg',
            'mobile'   => $mobile,
            'email'    => '',
            'sex'      => $_sex,
            'city'     => '成都市',
            'sign'     => '我签名：'.getChar($_nums),
            'status'   => 1,
            'openid'   => '',
            'from_uid' => 0,
            'ctime'    => $time,
            'mtime'    => $time,
        ];

        return $_row;
    }

    // 生成随机字符串
    protected function random($model, $num = 6)
    {
        // 去掉了 0 1 O l 等
        $str   = "abcdefghijkmnpqrstuvwxyz";  //ABCDEFGHIJKLMNPQRSTUVW 不要在写的
        $code  = '';
        $lenth = strlen($str);
        for($i = 0; $i < $num; $i++){
            $code .= $str[mt_rand(0, $lenth - 1)];
        }

        // 查询在数据库中是否已经存在
        $info = $model->where('salt', $code)->first();
        if(empty($info)){
            return $code;
        }

        return $this->random($model, $num);
    }
}
